<template>
  <!-- 浮动聊天按钮 -->
  <div 
    v-if="!isOpen"
    class="ai-chat-button"
    :style="buttonStyle"
    @mousedown="startDrag"
    @click="openChat"
    title="AI智能客服"
  >
    <div class="chat-icon">💬</div>
    <div class="chat-badge" v-if="unreadCount > 0">{{ unreadCount }}</div>
  </div>

  <!-- 聊天窗口 -->
  <div 
    v-if="isOpen"
    class="ai-chat-window"
    :style="windowStyle"
  >
    <!-- 标题栏 -->
    <div class="chat-header" @mousedown="startDrag">
      <div class="header-title">
        <span>🤖 AI智能客服</span>
        <span class="status-indicator" :class="{ 'online': isConnected }">
          {{ isConnected ? '在线' : '离线' }}
        </span>
      </div>
      <div class="header-actions">
        <button @click="minimizeChat" class="action-btn" title="最小化">−</button>
        <button @click="closeChat" class="action-btn" title="关闭">×</button>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="chat-messages" ref="messagesContainer">
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0" class="welcome-message">
        <div class="welcome-icon">👋</div>
        <h3>您好！我是AI智能客服</h3>
        <p>我可以帮您解答关于仓库管理系统的问题</p>
        <div class="quick-questions">
          <button @click="askQuestion('如何查询库存？')" class="quick-btn">如何查询库存？</button>
          <button @click="askQuestion('如何创建入库单？')" class="quick-btn">如何创建入库单？</button>
          <button @click="askQuestion('如何处理订单？')" class="quick-btn">如何处理订单？</button>
        </div>
      </div>

      <!-- 聊天消息 -->
      <div 
        v-for="(msg, index) in messages" 
        :key="index"
        class="message-item"
        :class="msg.role"
      >
        <div class="message-avatar">{{ msg.role === 'user' ? '👤' : '🤖' }}</div>
        <div class="message-content">
          <div class="message-text" v-html="formatMessage(msg.content)"></div>
          <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
        </div>
      </div>

      <!-- 加载中 -->
      <div v-if="isLoading" class="message-item assistant">
        <div class="message-avatar">🤖</div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span><span></span><span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入框 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="2"
        placeholder="输入您的问题..."
        @keydown.enter.prevent="handleEnter"
        :disabled="isLoading"
      />
      <button 
        @click="sendMessage" 
        class="send-btn"
        :disabled="!inputMessage.trim() || isLoading"
      >
        {{ isLoading ? '⏳' : '📤' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, onUnmounted, getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();

// 状态管理
const isOpen = ref(false);
const isConnected = ref(true);
const isLoading = ref(false);
const inputMessage = ref('');
const messages = ref([]);
const unreadCount = ref(0);

// 拖拽相关
const position = reactive({
  x: window.innerWidth - 400,
  y: window.innerHeight - 600
});

const isDragging = ref(false);
const dragStart = reactive({ x: 0, y: 0 });

// 样式计算
const buttonStyle = computed(() => ({
  right: `${window.innerWidth - position.x - 60}px`,
  bottom: `${window.innerHeight - position.y - 60}px`
}));

const windowStyle = computed(() => ({
  left: `${position.x}px`,
  top: `${position.y}px`
}));

// 消息容器引用
const messagesContainer = ref(null);

const openChat = () => {
  isOpen.value = true;
  unreadCount.value = 0;
  nextTick(() => scrollToBottom());
};

const closeChat = () => {
  isOpen.value = false;
};

const minimizeChat = () => {
  isOpen.value = false;
};

const startDrag = (e) => {
  if (e.target.closest('.action-btn')) return;
  isDragging.value = true;
  dragStart.x = e.clientX - position.x;
  dragStart.y = e.clientY - position.y;
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  e.preventDefault();
};

const onDrag = (e) => {
  if (!isDragging.value) return;
  let newX = e.clientX - dragStart.x;
  let newY = e.clientY - dragStart.y;
  const maxX = window.innerWidth - (isOpen.value ? 400 : 60);
  const maxY = window.innerHeight - (isOpen.value ? 600 : 60);
  newX = Math.max(0, Math.min(newX, maxX));
  newY = Math.max(0, Math.min(newY, maxY));
  position.x = newX;
  position.y = newY;
};

const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isLoading.value) return;
  
  messages.value.push({
    role: 'user',
    content: message,
    timestamp: new Date()
  });
  
  inputMessage.value = '';
  isLoading.value = true;
  nextTick(() => scrollToBottom());
  
  try {
    const history = messages.value.slice(-11, -1).map(msg => ({
      role: msg.role,
      content: msg.content
    }));
    
    const response = await fetch('/api/AIChat/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
      },
      body: JSON.stringify({
        message: message,
        history: history
      })
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    
    const aiMessage = {
      role: 'assistant',
      content: '',
      timestamp: new Date()
    };
    messages.value.push(aiMessage);
    
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      
      const chunk = decoder.decode(value);
      const lines = chunk.split('\n\n');
      
      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim();
          if (data === '[DONE]') break;
          
          try {
            const json = JSON.parse(data);
            if (json.error) {
              aiMessage.content = `❌ ${json.error}`;
              break;
            }
            if (json.choices && json.choices[0]?.delta?.content) {
              aiMessage.content += json.choices[0].delta.content;
              nextTick(() => scrollToBottom());
            }
          } catch (e) {
            console.warn('解析响应失败:', e);
          }
        }
      }
    }
    
    if (!aiMessage.content) {
      aiMessage.content = '抱歉，AI暂时无法响应，请稍后再试。';
    }
    
  } catch (error) {
    console.error('发送消息失败:', error);
    messages.value.push({
      role: 'assistant',
      content: `抱歉，发生了错误：${error.message}`,
      timestamp: new Date()
    });
    proxy.$message.error('发送失败: ' + error.message);
  } finally {
    isLoading.value = false;
    nextTick(() => scrollToBottom());
  }
};

const askQuestion = (question) => {
  inputMessage.value = question;
  sendMessage();
};

const handleEnter = (e) => {
  if (e.shiftKey) return;
  e.preventDefault();
  sendMessage();
};

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

const formatMessage = (content) => {
  if (!content) return '';
  return content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>');
};

const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;
  if (diff < 60000) return '刚刚';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
};

const handleResize = () => {
  const maxX = window.innerWidth - (isOpen.value ? 400 : 60);
  const maxY = window.innerHeight - (isOpen.value ? 600 : 60);
  position.x = Math.min(position.x, maxX);
  position.y = Math.min(position.y, maxY);
};

onMounted(() => {
  window.addEventListener('resize', handleResize);
  console.log('🤖 AI客服组件已加载');
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  stopDrag();
});

defineExpose({ openChat, closeChat });
</script>

<style scoped lang="less">
.ai-chat-button {
  position: fixed;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  cursor: move;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  transition: transform 0.3s;
  &:hover { transform: scale(1.1); }
  .chat-icon { font-size: 30px; }
  .chat-badge {
    position: absolute;
    top: 5px;
    right: 5px;
    background: #f56c6c;
    color: white;
    border-radius: 10px;
    padding: 2px 6px;
    font-size: 12px;
  }
}

.ai-chat-window {
  position: fixed;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  z-index: 9999;
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  cursor: move;
  border-radius: 12px 12px 0 0;
  .header-title {
    display: flex;
    gap: 10px;
    align-items: center;
    .status-indicator {
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 10px;
      background: rgba(255, 255, 255, 0.2);
      &.online { background: rgba(103, 194, 58, 0.3); }
    }
  }
  .header-actions {
    display: flex;
    gap: 5px;
    .action-btn {
      width: 30px;
      height: 30px;
      border: none;
      background: rgba(255, 255, 255, 0.2);
      color: white;
      border-radius: 6px;
      cursor: pointer;
      font-size: 18px;
      &:hover { background: rgba(255, 255, 255, 0.3); }
    }
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}

.welcome-message {
  text-align: center;
  padding: 40px 20px;
  .welcome-icon { font-size: 48px; margin-bottom: 20px; }
  h3 { color: #303133; margin-bottom: 10px; }
  p { color: #909399; margin-bottom: 30px; }
  .quick-questions {
    display: flex;
    flex-direction: column;
    gap: 10px;
    .quick-btn {
      padding: 12px 20px;
      background: white;
      border: 1px solid #dcdfe6;
      border-radius: 8px;
      cursor: pointer;
      &:hover { border-color: #667eea; color: #667eea; }
    }
  }
}

.message-item {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  &.user {
    flex-direction: row-reverse;
    .message-content { align-items: flex-end; }
    .message-text {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
  }
  .message-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: #e4e7ed;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
  }
  .message-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 5px;
    max-width: 70%;
    .message-text {
      padding: 12px 16px;
      border-radius: 12px;
      background: white;
      line-height: 1.6;
      word-wrap: break-word;
    }
    .message-time {
      font-size: 12px;
      color: #909399;
      padding: 0 5px;
    }
  }
}

.typing-indicator {
  display: flex;
  gap: 5px;
  padding: 12px 16px;
  background: white;
  border-radius: 12px;
  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #909399;
    animation: typing 1.4s infinite;
    &:nth-child(2) { animation-delay: 0.2s; }
    &:nth-child(3) { animation-delay: 0.4s; }
  }
}

@keyframes typing {
  0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
  30% { opacity: 1; transform: translateY(-10px); }
}

.chat-input {
  padding: 15px 20px;
  background: white;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 10px;
  align-items: flex-end;
  border-radius: 0 0 12px 12px;
  .send-btn {
    width: 40px;
    height: 40px;
    border: none;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 8px;
    cursor: pointer;
    font-size: 20px;
    &:disabled { opacity: 0.5; cursor: not-allowed; }
  }
}
</style>

